/**
 * @author: Miss.杨
 * @date: 2025年3月09日 09:08:00
 * @description: 
 */
package com.sheepone.monitor.audit;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.sheepone.monitor.audit.core.entities.AuditLogContext;
import com.sheepone.monitor.audit.core.entities.AuditLogMessage;
import com.sheepone.monitor.audit.server.ActionHandler;
import com.sheepone.monitor.audit.server.ActionRouter;
import com.sheepone.monitor.audit.server.GlobalServiceRouter;
import com.sheepone.monitor.audit.server.ModuleRouter;
import com.sheepone.monitor.enums.SerializationAlgorithmsEnum;
import com.sheepone.monitor.enums.SheeponePackageTypeEnum;
import com.sheepone.monitor.handler.AbstractSheeponeContentDuplexHandler;
import com.sheepone.monitor.proto.AuditLogMessageRequest;
import com.sheepone.monitor.proto.AuditLogMessageResponse;
import com.sheepone.monitor.proto.AuditLogMessageResponse.Builder;
import com.sheepone.webdev.log.WebDevLogger;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author: Miss.杨
 * @date: 2025年3月09日 09:08:00
 * @description:
 */
@Sharable
public class SheeponeAuditLogServerHandler
        extends AbstractSheeponeContentDuplexHandler<AuditLogMessageRequest, AuditLogMessageResponse> {
    public SheeponeAuditLogServerHandler() {
        super(SheeponePackageTypeEnum.AUDIT_LOG_REQUEST, SheeponePackageTypeEnum.AUDIT_LOG_RESPONSE,
                SerializationAlgorithmsEnum.PROTOBUF);
    }

    private WebDevLogger logger = WebDevLogger.getLogger(SheeponeAuditLogServerHandler.class);

    @Override
    public byte[] toBytes(AuditLogMessageResponse content, SerializationAlgorithmsEnum serialization) throws Exception {
        return content.toByteArray();
    }

    @Override
    public AuditLogMessageRequest fromBytes(byte[] bytes, SerializationAlgorithmsEnum serialization) throws Exception {
        return AuditLogMessageRequest.parseFrom(bytes);
    }

    private AuditLogMessage getAuditLogMessage(AuditLogMessageRequest request) {
        AuditLogMessage message = new AuditLogMessage();
        // TODO 必要参数验证 and 非必要参数采取默认值
        message.setAction(request.getAction());
        message.setAppId(request.getAppId());
        message.setDuration(request.getDuration());
        message.setModule(request.getModule());
        message.setService(request.getService());
        message.setStatus(request.getStatus());
        message.setUserId(request.getUserId());
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        LocalDateTime dateTime = LocalDateTime.parse(request.getRequestTime(), isoFormatter);
        message.setRequestTime(dateTime);
        return message;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AuditLogMessageRequest msg) throws Exception {
        AuditLogMessage message = getAuditLogMessage(msg);
        String service = message.getService();
        String module = message.getModule();
        String action = message.getAction();
        ModuleRouter moduleRouter = GlobalServiceRouter.route(service);
        if (moduleRouter == null) {
            logger.warn("ModuleRouter for service:{} is null", service);
            return;
        }
        ActionRouter actionRouter = moduleRouter.route(module);
        if (actionRouter == null) {
            logger.warn("ActionRouter for service:{} module:{} is null", service, module);
            return;
        }
        ActionHandler<?> actionHandler = actionRouter.route(action);
        if (actionHandler == null) {
            logger.warn("ActionHandler for service:{} module:{} action:{} is null", service, module, action);
            return;
        }
        actionHandler.handle(new AuditLogContext(message));
        // TODO 返回数据到客户端
        Builder newBuilder = AuditLogMessageResponse.newBuilder();
        newBuilder.setCode("200");
        newBuilder.setMessage("success");
        newBuilder.setData("true");
        ctx.writeAndFlush(newBuilder.build());
    }

}
